package com.enjoy.xbase.qk.task;

import android.util.Log;

import com.enjoy.xbase.qk.bean.ERR;
import com.enjoy.xbase.qk.impi.RequestBack;
import com.enjoy.xbase.qk.impi.RequestInfo;
import com.enjoy.xbase.qk.model.CommonModel;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Response;


/**
 * Created by cxb on 2018/6/25.
 */

public class DeleteTask extends BaseTask {
    private CommonModel commonModel;
    private RequestInfo requestInfo;

    public DeleteTask(CommonModel commonModel, RequestBack back, RequestInfo requestInfo) {
        super(commonModel, back, requestInfo);
        this.commonModel = commonModel;
        this.requestInfo = requestInfo;
    }

    public void run() {
        if (commonModel.getTag() != null && !"".equals(commonModel.getTag())) {
            try {
                Thread.sleep(commonModel.getWaitTime());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!requestInfo.isLast(commonModel.getTag(), commonModel.getRequestTime())) return;
        }
        handleURL();

        Log.i(":delete请求", commonModel.getUrl());
        FormBody formBody = new FormBody.Builder().build();

        okhttp3.Request.Builder builder = new okhttp3.Request.Builder()
                .url(commonModel.getUrl())
                .tag(commonModel.getTagId() == null ? "" : commonModel.getTagId())
                .delete(formBody);

        for (Map.Entry<String, String> header : commonModel.getHeaders().entrySet()) {
            if (header != null) {
                builder.addHeader(header.getKey(), header.getValue());
            }
        }
        okhttp3.Request request = builder.build();

        OkHttpClient client = requestInfo.getClient();//创建OkHttpClient对象。

        Call call = client.newCall(request);

        requestInfo.addCall(call);

        //execute的方法是同步方法，
        //enqueue的方法是异步方法，

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requestInfo.removeCall(call);
                if (call.isCanceled()) {//关闭界面的取消请求执行这里
                    Log.e("aaaa", "用户取消了这次请求" + call.request().url());
                    setBackCancel();
                } else {
                    setBackFail(ERR.ERR_NET);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                requestInfo.removeCall(call);
                Log.d("net", "获取数据成功了");
                Log.d("net", "response.code()==" + response.code());
                try {
                    setResultData(response.body().string());
                } catch (IOException e) {
                    setBackFail(ERR.ERR_NET);
                    Log.d("net", "网络异常中断");
                }
            }
        });
    }

    public void handleURL() {
        if (commonModel.getParameter_file().size() > 0 || hasObj()) {
            throw new RuntimeException("传输含有对象或文件不能使用Method.GET");
        } else if (commonModel.getParameter_obj().size() > 0) {
            StringBuilder url = new StringBuilder(commonModel.getUrl());
            if (!url.toString().contains("?")) url.append("?");
            for (Map.Entry<String, Object> itemFile : commonModel.getParameter_obj().entrySet()) {
                if (itemFile != null) {
                    String key = itemFile.getKey();
                    Object value = itemFile.getValue();
                    url.append(URLEncoder.encode(key)).append("=").append(URLEncoder.encode(value + "")).append("&");
                }
            }
            commonModel.setUrl(url.substring(0, url.length() - 1));
        }
    }

    private boolean hasObj() {
        if (commonModel.getParameter_file().size() > 0) {
            return true;
        }
        for (Map.Entry<String, Object> itemFile : commonModel.getParameter_obj().entrySet()) {
            if (itemFile != null) {
                Object value = itemFile.getValue();
                if (!isPrimitive(value)) return true;
            }
        }
        return false;
    }

    private boolean isPrimitive(Object obj) {
        boolean baseType;
        try {
            baseType = ((Class<?>) obj.getClass().getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
            baseType = false;
        }
        if (baseType) {
            return true;
        } else if (obj instanceof String) {
            return true;
        }
        return false;
    }
}
